﻿using PagedList;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Mitek.Models.Auth;
using Mitek.Repositories.Interfaces;
using Mitek.Repositories.Interfaces.Auth;
using Mitek.Services.Interfaces;
using Mitek.Repositories;
using Mitek.Services.Auth;
using Mitek.Utils.Security;

namespace Mitek.Services.Auth
{
    public class UserService : BaseService<User>, IUserService
    {
        private readonly IUserRepository _userRepository;
        private readonly IUserRoleRepository _userroleRepository;
        private readonly IUnitOfWork _unitOfWork;

        public UserService(IUserRepository userRepository,IUserRoleRepository userroleRepository,IUnitOfWork unitOfWork)
            : base(userRepository, unitOfWork)
        {
            this._userRepository = userRepository;
            this._userroleRepository = userroleRepository;
            this._unitOfWork = unitOfWork;
        }

        public User UserLogin(string username, string password)
        {
            
            string encryptPwd = Encrypt.Md5Encrypt(password);
            return _userRepository.Get(o => (o.UserName == username || o.Mobile == username) && o.PassWord == encryptPwd);
        }

        public User GetUserByID(int id)
        {
            return _userRepository.GetById(id);
        }

        public User GetUserByMobile(string mobile)
        {
            return _userRepository.GetAll().Where(o =>o.Mobile==mobile && o.IsDeleted==false).FirstOrDefault();
        }

        public List<User> GetUserByHid()
        {
            return _userRepository.GetAll().Where(o => o.RoleID==2 && o.IsDeleted==false).ToList();
        }

        public List<User> GetUserByRoleID(int roleid)
        {
            return _userRepository.GetAll().Where(o => o.RoleID == roleid && o.IsDeleted == false).ToList();
        }

        public List<UserRole> GetUserRoles()
        {
            return _userroleRepository.GetAll().ToList();
        }

        public void AddUser(User user)
        {
            _userRepository.Add(user);
            _unitOfWork.Commit();
        }

        public void UpdateUser(User user)
        {
            _userRepository.Update(user);
            _unitOfWork.Commit();
        }


        ///管理员获得所有用户
        public IPagedList<User> GetUsers(int page, int size)
        {
            var query = _userRepository.GetAll();
            return query.GetPage(e => e.ID, page, size, true);
        }
    }
}
